package com.wangzhixuan.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wangzhixuan.commons.result.PageInfo;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.Craftsman;
import com.wangzhixuan.model.Production;
import com.wangzhixuan.model.Productionimg;
import com.wangzhixuan.model.Producttag;
import com.wangzhixuan.model.TTag;
import com.wangzhixuan.service.ICraftsmanService;
import com.wangzhixuan.service.IProductionService;
import com.wangzhixuan.service.IProductionimgService;
import com.wangzhixuan.service.IProducttagService;
import com.wangzhixuan.service.ITTagService;
import com.wangzhixuan.commons.base.BaseController;

/**
 * <p>
 * 用户角色 前端控制器
 * </p>
 *
 * @author zhixuan.wang
 * @since 2017-06-24
 */
@Controller
@RequestMapping("/production")
public class ProductionController extends BaseController {

    @Autowired private IProductionService productionService;
    @Autowired private IProductionimgService productionimgService;
    @Autowired private IProducttagService producttagService;
    @Autowired private ICraftsmanService craftsmanService;
    //@Autowired private ITTagService tTagService;
    
    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
    	SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    	dateFormat.setLenient(false);  
	    dateFormat1.setLenient(false); 
	    
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat1, true)); 
    }
    
    @GetMapping("/manager")
    public String manager( Model model,Long id) {
    	 model.addAttribute("id", id);
        return "admin/production/productionList";
    }
    
    
    @PostMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(Production production, Integer page, Integer rows, String sort,String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Page<Production> pages = getPage(pageInfo);
        pages = productionService.selectPageProductionForList(pages, production);
        pageInfo.setRows(pages.getRecords());
        pageInfo.setTotal(pages.getTotal());
        return pageInfo;
    }
    
    /**
     * 添加页面
     * @return
     */
    @GetMapping("/addPage")
    public String addPage(Model model) {
    	//获取标签列表
    	List<Producttag> tagList=producttagService.listSelTag(null);
    	model.addAttribute("tagList",tagList);
    	
    	//获取品牌列表
    	EntityWrapper<Craftsman> ew = new EntityWrapper<Craftsman>();
    	ew.orderBy("man_brand");
        List<Craftsman>  brandList= craftsmanService.selectList(ew);
        model.addAttribute("brandList",brandList);
        
        return "admin/production/productionAdd";
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(@Valid Production production,HttpServletRequest request) {
    	try {
    		Craftsman craftsMan=craftsmanService.selectById(production.getCarftsmanId());
    		production.setManKey(craftsMan.getManKey());
    		 boolean b = productionService.insert(production);
    		 if (b) {
    			 String[] tags=request.getParameterValues("protags");
    			 if(tags!=null && tags.length>0){
    				 for(String tag:tags){
    					 if(StringUtils.isNotBlank(tag)){
    						 Producttag ptagVO=new Producttag();
    						 ptagVO.setCreateTime(new Date());
    						 ptagVO.setPruductid(production.getId());
    						 ptagVO.setProductKey(production.getManProductKey());
    						 ptagVO.setTagid(Long.parseLong(tag));
    						 producttagService.insert(ptagVO);
    					 }
    				 }
    			 }
    			 
		    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				String pathRoot = request.getSession().getServletContext().getRealPath("");  
				String dir="/upload/images/"+production.getManKey()+"/"+production.getManProductKey()+"/";
				// 封面图片
				MultipartFile file = multipartRequest.getFile("pic_manCove");
				if(file != null && file.getSize()>0) {
					String path=this.saveImg(pathRoot,dir, file);
		            production.setManCover(path);
		            productionService.updateById(production);
				}
				
				List<MultipartFile> files=multipartRequest.getFiles("upproimg");
				if(files!=null && files.size()>0){
					for(int i=0;i<files.size();i++){
						MultipartFile tempfile =files.get(i);
						if(tempfile != null && tempfile.getSize()>0) {
							if(tempfile!=null && tempfile.getSize()>0){
								String path=this.saveImg(pathRoot,dir, tempfile);
								Productionimg pimgVO=new Productionimg();
					            pimgVO.setManProductKey(production.getManProductKey());
					            pimgVO.setManImg(path);
					            pimgVO.setProdoctId(production.getId());
					            productionimgService.insert(pimgVO);
							}
						}
					}
				}
    		 } else {
    			 return renderError("添加失败！");
 	        }
		 } catch (Exception e) {
				e.printStackTrace();
		}
    	return renderSuccess("添加成功！");
       
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        Production production = new Production();
        production.setId(id);
        boolean b = productionService.deleteById(id);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
    	//查询产品信息
        Production production = productionService.selectById(id);
        model.addAttribute("production", production);
        
        //获取产品图片列表
        Map<String, Object> columnMap=new HashMap<String, Object> ();
        List<Productionimg> proimgList=null;
        if(StringUtils.isNotBlank(production.getManProductKey())){
	        columnMap.put("man_product_key",production.getManProductKey());
	        proimgList=productionimgService.selectByMap(columnMap);
        }
        if(proimgList==null){
        	proimgList=new ArrayList<Productionimg>();
        	proimgList.add(new Productionimg());
        }
        if(proimgList.size()<5){
        	for(int i=0;i<5-proimgList.size();i++){
        		proimgList.add(new Productionimg());
        	}
        }
        model.addAttribute("proimgList", proimgList);
        
        
        //获取品牌列表
        EntityWrapper<Craftsman> ew = new EntityWrapper<Craftsman>();
    	ew.orderBy("man_brand");
        List<Craftsman>  brandList= craftsmanService.selectList(ew);
        model.addAttribute("brandList",brandList);
        
        //获取标签列表
        Producttag ptag=new Producttag();
        if(StringUtils.isNotBlank(production.getManProductKey())){
        	 ptag.setProductKey(production.getManProductKey());
        }else{
        	 ptag.setPruductid(production.getId());
        }
        List<Producttag> tagList=producttagService.listSelTag(ptag);
    	model.addAttribute("tagList",tagList);
    	
        //指定跳转页面
        return "admin/production/productionEdit";
    }
    
    @GetMapping("/viewProductPage")
    public String viewProductPage(Model model, Long id) {
        Production production = productionService.selectById(id);
        model.addAttribute("production", production);
        return "admin/production/productionEdit";
    }
    
    public String saveImg(String pathRoot,String dir,MultipartFile file){
    	String imgPath=null;
    	if(file != null && file.getSize()>0) {
    		String uuid = UUID.randomUUID().toString().replaceAll("-","");  
			//获得文件类型（可以判断如果不是图片，禁止上传）  
            String contentType=file.getContentType();  
            //获得文件后缀名称  
            String imageName=contentType.substring(contentType.indexOf("/")+1);  
            String path=dir+uuid+"."+imageName;  
            File tFile=new File(pathRoot+path);
            if(!tFile.getParentFile().exists()){
            	tFile.mkdirs();
            }
			try {
				file.transferTo(tFile);
				return path;
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	return imgPath;
    }
    /**
     * 编辑
     * @param 
     * @return
     */
	@PostMapping("/edit")
    @ResponseBody
    public Object edit(@Valid Production production,HttpServletRequest request) {
    	 try {
    		 
    		 Craftsman craftsMan=craftsmanService.selectById(production.getCarftsmanId());
     		 production.setManKey(craftsMan.getManKey());
     		
    		 //清空原来Tag信息
    		 Map<String, Object> columnMap1=new HashMap<String, Object>();
    		 columnMap1.put("product_key", production.getManProductKey());
    		 producttagService.deleteByMap(columnMap1);
    		 Map<String, Object> columnMap2=new HashMap<String, Object>();
    		 columnMap2.put("product_key", production.getId());
    		 producttagService.deleteByMap(columnMap2);
    		 //重新入库
    		 String[] tags=request.getParameterValues("protags");
			 if(tags!=null && tags.length>0){
				 for(String tag:tags){
					 if(StringUtils.isNotBlank(tag)){
						 Producttag ptagVO=new Producttag();
						 ptagVO.setCreateTime(new Date());
						 ptagVO.setPruductid(production.getId());
						 ptagVO.setProductKey(production.getManProductKey());
						 ptagVO.setTagid(Long.parseLong(tag));
						 producttagService.insert(ptagVO);
					 }
				 }
			 }
			
	    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String pathRoot = request.getSession().getServletContext().getRealPath("");  
			String dir="/upload/images/"+production.getManKey()+"/"+production.getManProductKey()+"/";
			// 封面图片
			MultipartFile file = multipartRequest.getFile("pic_manCove");
			if(file != null && file.getSize()>0) {
				String path=this.saveImg(pathRoot,dir, file);
	            production.setManCover(path);
			}
			
			//清空原来图片信息
	   		//productionimgService.deleteImgsByProductKey(pathRoot,production.getManProductKey());
			//重新入库
			List<MultipartFile> files=multipartRequest.getFiles("upproimg");
			String[] imgids=request.getParameterValues("imagIds");
			if(files!=null && files.size()>0){
				for(int i=0;i<files.size();i++){
					MultipartFile tempfile =files.get(i);
					if(tempfile != null && tempfile.getSize()>0) {
						if(tempfile!=null && tempfile.getSize()>0){
							String path=this.saveImg(pathRoot,dir, tempfile);
							Productionimg pimgVO=new Productionimg();
				            pimgVO.setManProductKey(production.getManProductKey());
				            pimgVO.setManImg(path);
				            pimgVO.setProdoctId(production.getId());
				            productionimgService.insert(pimgVO);
				            if(StringUtils.isNotBlank(imgids[i])){
				            	Long imgid=Long.parseLong(imgids[i]);
				            	if(imgid>0){
				            		Productionimg oldImgVO=productionimgService.selectById(imgid);
				            		File oldimgfile=new File(dir+oldImgVO.getManImg());
				         		    if(oldimgfile.exists() && oldimgfile.isFile()){
				         		    	oldimgfile.delete();
				         		    }
				         		   productionimgService.deleteById(oldImgVO.getId());
				            	}
				            }
						}
					}
				}
			}
			 boolean b = productionService.updateById(production);
    		 if (!b) {
  	            return renderError("编辑失败！");
  	         }else{
  	        	 return renderSuccess("编辑成功！");
  	         }
		 } catch (Exception e) {
			e.printStackTrace();
		 }
    	 return renderError("编辑失败！");
   }
    

    
}
